package com.hongmeng.teamwork.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.hongmeng.teamwork.constants.HttpHeadConstant;
import com.hongmeng.teamwork.domain.ITeamworkProjectDomainService;
import com.hongmeng.teamwork.entity.base.Result;
import com.hongmeng.teamwork.entity.dto.TeamworkProjectDto;
import com.hongmeng.teamwork.entity.dto.UserDto;
import com.hongmeng.teamwork.entity.po.User;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Log4j2
@RestController
@RequestMapping("/project")
public class TeamworkProjectController {

    @Resource
    private ITeamworkProjectDomainService teamworkProjectDomainService;

    @PostMapping("/save")
    public Result<?> save(@RequestHeader(HttpHeadConstant.ACCESS_TOKEN) String accessToken,
                            @RequestBody TeamworkProjectDto projectDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("TeamworkProjectController.save.dto: {}", JSON.toJSONString(projectDto));
            }
            Preconditions.checkArgument(StringUtils.isNoneBlank(projectDto.getName()), "项目名称不能为空！");
            UserDto createdUser = projectDto.getCreatedUser();
            Preconditions.checkNotNull(createdUser, "创建人数据不能为空！");
            Preconditions.checkArgument(StringUtils.isNoneBlank(createdUser.getName()), "创建人名字不能为空！");
            Preconditions.checkArgument(StringUtils.isNoneBlank(createdUser.getAvatarUrl()), "创建人头像不能为空！");
            Preconditions.checkArgument(StringUtils.isNoneBlank(projectDto.getOpenId()), "openId 不能为空！");
            projectDto.setAccessToken(accessToken);
            teamworkProjectDomainService.save(projectDto);
            return Result.ok("新增项目成功！");
        } catch (Exception e) {
            log.error("TeamworkProjectController.save.error: {}", e.getMessage(), e);
            return Result.fail("新增项目失败！");
        }
    }

    @GetMapping("/query")
    public Result<?> query(TeamworkProjectDto projectDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("TeamworkProjectController.query.openId: {}", JSON.toJSONString(projectDto));
            }
            Preconditions.checkArgument(StringUtils.isNoneBlank(projectDto.getOpenId()), "openId 不能为空！");
            return Result.ok(teamworkProjectDomainService.query(projectDto));
        } catch (Exception e) {
            log.error("TeamworkProjectController.query.error: {}", e.getMessage(), e);
            return Result.fail("查询项目失败！");
        }
    }
}
